package com.bbznb.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.util.Date;

public class JwtUtil {
    private static final String SECRET_KEY = "NDA0NzE3MDA2MTY1NjU3NTE1NDU0NDcwMzM0MzM3NTQ="; // 密钥
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    // 生成JWT
    public static String generateToken(String username) {
        return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 解析JWT
    public static Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(token)
                .getBody();
    }

    // 验证JWT
    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (SignatureException e) {
            System.out.println("无效签名: " + e.getMessage());
        } catch (MalformedJwtException e) {
            System.out.println("无效JWT: " + e.getMessage());
        } catch (ExpiredJwtException e) {
            System.out.println("JWT已过期: " + e.getMessage());
        } catch (UnsupportedJwtException e) {
            System.out.println("不支持的JWT: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            System.out.println("JWT为空: " + e.getMessage());
        }
        return false;
    }

//    public static void main(String[] args) {
//        // 示例用法
//        String token = generateToken("testUser");
//        System.out.println("生成的JWT: " + token);
//
//        if (validateToken(token)) {
//            Claims claims = parseToken(token);
//            System.out.println("用户名: " + claims.getSubject());
//            System.out.println("签发时间: " + claims.getIssuedAt());
//            System.out.println("过期时间: " + claims.getExpiration());
//        }
//    }
}